package com.ccrfid.rmc6.service.business.nightpatrol;

import com.ccrfid.rmc6.appconfig.exception.pojo.AppException;
import com.ccrfid.rmc6.appconfig.exception.pojo.CustomErrors;
import com.ccrfid.rmc6.entity.business.nightpatrol.*;
import com.ccrfid.rmc6.entity.personnel.PersonnelMoveEntity;
import com.ccrfid.rmc6.pojo.param.PageParam;
import com.ccrfid.rmc6.repository.business.nightPatrol.*;
import com.ccrfid.rmc6.repository.personnel.PersonnelMoveRepository;
import com.ccrfid.rmc6.repository.personnel.PersonnelRepository;
import com.ccrfid.rmc6.repository.poi.PoiLocationRepository;
import com.ccrfid.rmc6.repository.search.SearchCriteria;
import com.ccrfid.rmc6.util.DateUtil;
import com.ccrfid.rmc6.util.GeomUtil;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import javax.ws.rs.core.Response;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.springframework.data.jpa.repository.query.QueryUtils.toOrders;

@Service
@Transactional
public class NightPatrolServiceImpl implements NightPatrolService {
    private static final Logger logger = LoggerFactory.getLogger(NightPatrolServiceImpl.class);

    @Autowired
    private NpGroupRepository npGroupRepository;

    @Autowired
    private NpGroupMemberRepository npGroupMemberRepository;

    @Autowired
    private NpResultRepository npResultRepository;

    @Autowired
    private NpResultDetailRepository npResultDetailRepository;

    @Autowired
    private PersonnelRepository personnelRepository;

    @Autowired
    private NpGroupViewRepository npGroupViewRepository;

    @Autowired
    private PersonnelMoveRepository personnelMoveRepository;

    @Autowired
    private PoiLocationRepository poiLocationRepository;

    @PersistenceContext
    private EntityManager entityManager;

    @Value("${timelate}")
    private Long timelate;

    @Override
    public List<NpGroupEntity> getAllPcGroups() {
        return npGroupRepository.getAllBy();
    }

    @Override
    public List<NpGroupMemberEntity> getAllGroupMembersByGroupId(Long groupId) {
        return npGroupMemberRepository.getByGroupId(groupId);
    }

    @Override
    public Long createNpGroup(NpGroupEntity npGroupEntity) throws AppException {
        if (npGroupRepository.existsByGroupName(npGroupEntity.getGroupName())) {
            throw new AppException(Response.Status.CONFLICT.getStatusCode(),
                    CustomErrors.check_np_group_name_is_used.getCode(), CustomErrors.check_np_group_name_is_used.getReason(), "");
        }
        checkGroupParam(npGroupEntity);
        npGroupEntity.setStartLocationCentroid(poiLocationRepository.getById(npGroupEntity.getStartPatrolPlaceId()).getLocationCentroid());
        npGroupEntity.setStartLocationPolygon(poiLocationRepository.getById(npGroupEntity.getStartPatrolPlaceId()).getLocationPolygon());
        npGroupEntity.setEndLocationCentroid(poiLocationRepository.getById(npGroupEntity.getEndPatrolPlaceId()).getLocationCentroid());
        npGroupEntity.setEndLocationPolygon(poiLocationRepository.getById(npGroupEntity.getEndPatrolPlaceId()).getLocationPolygon());
        npGroupRepository.save(npGroupEntity);
        return npGroupEntity.getId();
    }

    @Override
    public Boolean createNpGroupMemberInfo(NpGroupMemberEntity npGroupMemberEntity, Long groupId) throws AppException {
        if (!npGroupRepository.existsById(groupId)) {
            throw new AppException(Response.Status.NOT_FOUND.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        if (!personnelRepository.existsById(npGroupMemberEntity.getPersonnelId())) {
            throw new AppException(Response.Status.NOT_FOUND.getStatusCode(),
                    CustomErrors.person_not_found.getCode(), CustomErrors.person_not_found.getReason(), "");
        }
        npGroupMemberEntity.setGroupId(groupId);
        npGroupMemberRepository.save(npGroupMemberEntity);
        return true;
    }

    public void checkGroupParam(NpGroupEntity npGroupEntity) throws AppException {
        if (StringUtils.isEmpty(npGroupEntity.getGroupName())) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.check_np_group_name_is_null.getCode(), CustomErrors.check_np_group_name_is_null.getReason(), "");
        }
        if (StringUtils.isEmpty(npGroupEntity.getStartPatrolPlace())) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.check_np_start_patrol_place_is_null.getCode(), CustomErrors.check_np_start_patrol_place_is_null.getReason(), "");
        }
        if (StringUtils.isEmpty(npGroupEntity.getEndPatrolPlace())) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.check_np_end_patrol_place_is_null.getCode(), CustomErrors.check_np_end_patrol_place_is_null.getReason(), "");
        }
        if (StringUtils.isEmpty(npGroupEntity.getStartTime())) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.check_np_start_time_is_null.getCode(), CustomErrors.check_np_start_time_is_null.getReason(), "");
        }
        if (StringUtils.isEmpty(npGroupEntity.getEndTime())) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.check_np_end_time_is_null.getCode(), CustomErrors.check_np_end_time_is_null.getReason(), "");
        }
        if (StringUtils.isEmpty(npGroupEntity.getTimeLength())) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.check_np_time_length_is_null.getCode(), CustomErrors.check_np_time_length_is_null.getReason(), "");
        }
    }

    @Override
    public Page<NpGroupViewEntity> getNpGroupView(SearchCriteria criteria, Pageable pageable) {
        return npGroupViewRepository.search(criteria, pageable);
    }

    @Override
    public Page<NpGroupViewEntity> getRcRecordList(String groupName, String personnelName, String patrolPlace, String patrolTime, PageParam pageParam, Pageable pageable) {

        CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
        CriteriaQuery<NpGroupViewEntity> pageCriteria = builder.createQuery(NpGroupViewEntity.class);
        Root<NpGroupViewEntity> pageRoot = pageCriteria.from(NpGroupViewEntity.class);
        List<Predicate> predicateList = new ArrayList<>();

        if (groupName != null) {
            predicateList.add(builder.like(pageRoot.get("groupName"), "%" + groupName + "%"));
        }
        if (personnelName != null) {
            predicateList.add(builder.like(pageRoot.get("groupMembers"), "%" + personnelName + "%"));
        }
        if (patrolPlace != null) {
            predicateList.add(builder.like(pageRoot.get("patrolPlace"), "%" + patrolPlace + "%"));
        }
        if (patrolTime != null) {
            String[] time = patrolTime.split(",");
            Date startTime = DateUtil.parseDateTimeStr(time[0].toString());
            Date endTime = DateUtil.parseDateTimeStr(time[1].toString());
            predicateList.add(
                    builder.and(builder.greaterThanOrEqualTo(pageRoot.get("startTime"), startTime)));
            predicateList.add(
                    builder.and(builder.lessThanOrEqualTo(pageRoot.get("endTime"), endTime)));

        }

        List<NpGroupViewEntity> list = this.entityManager.createQuery(
                pageCriteria.select(pageRoot)
                        .where(predicateList.toArray(new Predicate[predicateList.size()]))
                        .orderBy(toOrders(
                                Sort.by(
                                        (pageParam.getOrders() != null && pageParam.getOrders().size() > 0)
                                                ? pageParam.getOrders()
                                                : new ArrayList<>()
                                ), pageRoot, builder
                        ))).getResultList();

        return new PageImpl<>(new ArrayList<>(list), pageable, list.size());
    }

    @Override
    public Boolean deleteNpGroup(Long groupId) throws AppException {
        if (!npGroupRepository.existsById(groupId)) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        npGroupRepository.deleteById(groupId);
        if (npGroupMemberRepository.existsAllByGroupId(groupId)) {
            npGroupMemberRepository.deleteAllByGroupId(groupId);
        }
        return true;
    }

    @Override
    public Boolean updateNpGroupInfo(Long groupId, NpGroupEntity npGroupEntity) throws AppException {
        if (!npGroupRepository.existsById(groupId)) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        npGroupEntity.setStartLocationCentroid(poiLocationRepository.getById(npGroupEntity.getStartPatrolPlaceId()).getLocationCentroid());
        npGroupEntity.setStartLocationPolygon(poiLocationRepository.getById(npGroupEntity.getStartPatrolPlaceId()).getLocationPolygon());
        npGroupEntity.setEndLocationCentroid(poiLocationRepository.getById(npGroupEntity.getEndPatrolPlaceId()).getLocationCentroid());
        npGroupEntity.setEndLocationPolygon(poiLocationRepository.getById(npGroupEntity.getEndPatrolPlaceId()).getLocationPolygon());
        checkGroupParam(npGroupEntity);
        npGroupEntity.setId(groupId);

        npGroupRepository.save(npGroupEntity);
        return true;
    }

    @Override
    public Boolean deleteNpGroupMembers(Long groupId, Long memberId) throws AppException {
        if (!npGroupMemberRepository.existsByGroupIdAndPersonnelId(groupId, memberId)) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        npGroupMemberRepository.deleteAllByGroupIdAndPersonnelId(groupId, memberId);
        return true;
    }

    @Override
    public Page<NpResultEntity> getNpResultInfo(String startPatrolPlace, String patrolTime, String groupName,
                                                PageParam pageParam, Pageable pageable) {


        CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
        CriteriaQuery<NpResultEntity> pageCriteria = builder.createQuery(NpResultEntity.class);
        Root<NpResultEntity> pageRoot = pageCriteria.from(NpResultEntity.class);
        List<Predicate> predicateList = new ArrayList<>();
        if (StringUtil.isBlank(patrolTime)) {
            patrolTime = getForeDate();
        }
        try {
            if (groupName != null) {
                saveNpResultinfoForQuery(groupName, patrolTime);
            }
        } catch (AppException e) {
            logger.error("实时保存人员巡更数据失败！", e);
        }
        if (groupName != null) {
            predicateList.add(builder.like(pageRoot.get("groupName"), "%" + groupName + "%"));
        }
        if (startPatrolPlace != null) {
            predicateList.add(builder.like(pageRoot.get("startPatrolPlace"), "%" + startPatrolPlace + "%"));
        }
        if (patrolTime != null) {
            Date startTime = DateUtil.parseDateTimeStr(patrolTime.toString() + " 00:00:00");
            Date stopTime = DateUtil.parseDateTimeStr(patrolTime.toString() + " 23:59:59");
            predicateList.add(builder.and(builder.greaterThanOrEqualTo(pageRoot.get("startTime"), startTime)));
            predicateList.add(builder.and(builder.lessThanOrEqualTo(pageRoot.get("startTime"), stopTime)));
        }
        List<NpResultEntity> list = this.entityManager.createQuery(
                pageCriteria.select(pageRoot)
                        .where(predicateList.toArray(new Predicate[predicateList.size()]))
                        .orderBy(toOrders(
                                Sort.by(
                                        (pageParam.getOrders() != null && pageParam.getOrders().size() > 0)
                                                ? pageParam.getOrders()
                                                : new ArrayList<>()
                                ), pageRoot, builder
                        ))).getResultList();
        return new PageImpl<>(new ArrayList<>(list), pageable, list.size());
    }

    @Override
    public List<NpResultDetailEntity> getMpResultDetail(Long resultId) throws AppException {
        if (!npResultDetailRepository.existsByResultId(resultId)) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        return npResultDetailRepository.getByResultId(resultId);
    }

    @Override
    public void saveNpResultInfo(Long groupId, Date startTime, Date stopTime) throws AppException {
        List<NpResultDetailEntity> resultDetilList = getResultDeailList(groupId, startTime, stopTime);
        if (resultDetilList.size() > 0) {
            NpResultEntity npResultEntity = saveNpResult(groupId, resultDetilList, startTime);
            resultDetilList = checkDetailsStatu(resultDetilList, groupId, startTime);//检查每趟巡逻是否异常
            for (NpResultDetailEntity npResultDetailEntity : resultDetilList) {
                npResultDetailEntity.setResultId(npResultEntity.getId());
                if (!StringUtils.isEmpty(npResultDetailEntity.getBackStartTime()) && !StringUtils.isEmpty(npResultDetailEntity.getStartTime())) {
                    Long timeLength = (npResultDetailEntity.getBackStartTime().getTime() - npResultDetailEntity.getStartTime().getTime()) / 1000;
                    npResultDetailEntity.setTimeLength(timeLength);
                }
                npResultDetailRepository.save(npResultDetailEntity);
            }
        }
    }

    public List<NpResultDetailEntity> checkDetailsStatu(List<NpResultDetailEntity> resultDetilList, Long groupId, Date startTime) {
        NpGroupEntity npGroupEntity = npGroupRepository.getById(groupId);
        String date = DateUtil.toDateStr(startTime);
        //巡更开始时间
        Timestamp beginTIme = new Timestamp(DateUtil.parseDateTimeStr(date.toString() + " " + npGroupEntity.getStartTimePoint()).getTime());
        //巡更结束时间
        Timestamp endTIme = new Timestamp(DateUtil.parseDateTimeStr(date.toString() + " " + npGroupEntity.getEndTimePoint()).getTime());

        for (int i = 0; i < resultDetilList.size(); i++) {
            String statu1 = "0";
            String statu2 = "0";
            String statu3 = "0";
            String statu4 = "0";
            if (!StringUtils.isEmpty(resultDetilList.get(i).getBackStartTime()) && !StringUtils.isEmpty(resultDetilList.get(i).getStartTime())
                    && !StringUtils.isEmpty(resultDetilList.get(i).getEndTime())) {
                Long timeLength = (resultDetilList.get(i).getBackStartTime().getTime() - resultDetilList.get(i).getStartTime().getTime()) / 1000;
                if (npGroupEntity.getTimeLength() < timeLength) {
                    statu1 = "1";
                }
                if (i == 0) {//第一趟
                    Long startTimeLength = (resultDetilList.get(i).getStartTime().getTime() - beginTIme.getTime()) / 1000;
                    if (Math.abs(startTimeLength) > timelate * 60) {
                        statu3 = "1";
                    }
                }
                if (i == resultDetilList.size() - 1) {//最后一趟
                    Long endTimeLength = (endTIme.getTime() - resultDetilList.get(i).getBackStartTime().getTime()) / 1000;
                    if (Math.abs(endTimeLength) > timelate * 60) {
                        statu3 = "1";
                    }
                }
            } else {
                statu4 = "1";
            }
            String resultStatus = statu1 + statu2 + statu3 + statu4;
            resultDetilList.get(i).setResultStatus(resultStatus);
        }
        return resultDetilList;
    }


    //根据人员移动轨迹获取巡更详细信息
    public List<NpResultDetailEntity> getResultDeailList(Long groupId, Date startTime, Date stopTime) {
        List<NpGroupMemberEntity> npGroupMemberEntityList = npGroupMemberRepository.getByGroupId(groupId);
        List<NpResultDetailEntity> npResultDetailEntityList = new ArrayList<>();
        startTime = new Date(startTime.getTime() - timelate * 60 * 1000);
        stopTime = new Date(stopTime.getTime() + timelate * 60 * 1000);
        for (NpGroupMemberEntity npGroupMemberEntity : npGroupMemberEntityList) {
            NpResultDetailEntity npResultDetailEntity = new NpResultDetailEntity();
            NpGroupEntity npGroupEntity = npGroupRepository.getById(groupId);
            List<PersonnelMoveEntity> moveList =
                    personnelMoveRepository.getAllByPersonnelIdAndRecordTimeBetween(npGroupMemberEntity.getPersonnelId(),
                            startTime, stopTime);
//                for(PersonnelMoveEntity personnelMoveEntity : moveList){
            for (int i = 0; i < moveList.size(); i++) {
                npResultDetailEntity.setPersonnelId(npGroupMemberEntity.getPersonnelId());
                npResultDetailEntity.setPersonnelName(npGroupMemberEntity.getPersonnelName());
                npResultDetailEntity.setCardNumber(npGroupMemberEntity.getCardNumber());
                if (moveList.get(i).getCurrentX() != null
                        && moveList.get(i).getCurrentY() != null) {
                    if (npGroupEntity.getStartLocationPolygon().contains(
                            GeomUtil.INSTANCE.createPoint(moveList.get(i).getCurrentX(), moveList.get(i).getCurrentY()))) {
                        if (StringUtils.isEmpty(npResultDetailEntity.getStartTime()) && StringUtils.isEmpty(npResultDetailEntity.getEndTime())) {
                            npResultDetailEntity.setStartTime(moveList.get(i).getRecordTime());
                        } else if (!npGroupEntity.getStartLocationPolygon().contains(
                                GeomUtil.INSTANCE.createPoint(moveList.get(i - 1).getCurrentX(), moveList.get(i - 1).getCurrentY()))) {
                            npResultDetailEntity.setBackStartTime(moveList.get(i).getRecordTime());
                            npResultDetailEntityList.add(npResultDetailEntity);
                            npResultDetailEntity = new NpResultDetailEntity();
                            npResultDetailEntity.setStartTime(moveList.get(i).getRecordTime());
                            npResultDetailEntity.setEndTime(null);
                            npResultDetailEntity.setBackStartTime(null);
                        } else {
                            npResultDetailEntity.setStartTime(moveList.get(i).getRecordTime());
                        }
                    } else if (npGroupEntity.getEndLocationPolygon().contains(
                            GeomUtil.INSTANCE.createPoint(moveList.get(i).getCurrentX(), moveList.get(i).getCurrentY()))) {
                        if (StringUtils.isEmpty(npResultDetailEntity.getEndTime())) {
                            npResultDetailEntity.setEndTime(moveList.get(i).getRecordTime());
                        }
                        if (i == moveList.size() - 1 && !StringUtils.isEmpty(npResultDetailEntity.getStartTime())) {
                            npResultDetailEntityList.add(npResultDetailEntity);
                        }
                    }
                }
            }
        }
        return npResultDetailEntityList;
    }

    public NpResultEntity saveNpResult(Long groupId, List<NpResultDetailEntity> resultDetilList, Date startTime) {

        NpResultEntity npResultEntity = new NpResultEntity();
        NpGroupEntity npGroupEntity = npGroupRepository.getById(groupId);
        String date = DateUtil.toDateStr(startTime);
        npResultEntity.setGroupId(groupId);
        //判断巡更情况是否正常
        npResultEntity.setResultStatus(checkResultStatu(npGroupEntity, resultDetilList, startTime));
        npResultEntity.setGroupName(npGroupEntity.getGroupName());
        npResultEntity.setStartPatrolPlaceId(npGroupEntity.getStartPatrolPlaceId());
        npResultEntity.setStartPatrolPlace(npGroupEntity.getStartPatrolPlace());
        npResultEntity.setEndPatrolPlaceId(npGroupEntity.getEndPatrolPlaceId());
        npResultEntity.setEndPatrolPlace(npGroupEntity.getEndPatrolPlace());
        npResultEntity.setStartTime(new Timestamp(DateUtil.parseDateTimeStr(date.toString() + " " + npGroupEntity.getStartTimePoint()).getTime()));
        npResultEntity.setEndTime(new Timestamp(DateUtil.parseDateTimeStr(date.toString() + " " + npGroupEntity.getEndTimePoint()).getTime()));
        npResultEntity.setRecordTime(new Timestamp(new Date().getTime()));
        return npResultRepository.save(npResultEntity);
    }

    public int checkResultStatu(NpGroupEntity npGroupEntity, List<NpResultDetailEntity> resultDetilList, Date startTime) {
        int resultStatu = 0;
        for (NpResultDetailEntity npResultDetailEntity : resultDetilList) {
            if (!StringUtils.isEmpty(npResultDetailEntity.getBackStartTime()) && !StringUtils.isEmpty(npResultDetailEntity.getStartTime())) {
                Long timeLength = (npResultDetailEntity.getBackStartTime().getTime() - npResultDetailEntity.getStartTime().getTime()) / 1000;
                if (timeLength > npGroupEntity.getTimeLength()) {
                    resultStatu = 1;
                    break;
                }
            } else {
                resultStatu = 1;
                break;
            }
        }
        if (resultStatu == 0) {
            String date = DateUtil.toDateStr(startTime);
            NpResultDetailEntity firstEntity = resultDetilList.get(0);
            NpResultDetailEntity lastEntity = resultDetilList.get(resultDetilList.size() - 1);
            Timestamp beginTIme = new Timestamp(DateUtil.parseDateTimeStr(date.toString() + " " + npGroupEntity.getStartTimePoint()).getTime());
            Timestamp endTIme = new Timestamp(DateUtil.parseDateTimeStr(date.toString() + " " + npGroupEntity.getEndTimePoint()).getTime());
            Long startTimeLength = (firstEntity.getStartTime().getTime() - beginTIme.getTime()) / 1000;
            Long endTimeLength = (lastEntity.getBackStartTime().getTime() - endTIme.getTime()) / 1000;
            if (Math.abs(startTimeLength) > timelate * 60 || Math.abs(endTimeLength) > timelate * 60) {
                resultStatu = 1;
            }
        }
        return resultStatu;
    }

    public void saveNpResultinfoForQuery(String groupName, String patrolTime) throws AppException {

        Date startTime = DateUtil.parseDateTimeStr(patrolTime.toString() + " 00:00:00");
        Date stopTime = DateUtil.parseDateTimeStr(patrolTime.toString() + " 23:59:59");


        List<NpGroupEntity> npGroupEntityList = npGroupRepository.getAllByGroupNameLikeAndStartTimeLessThanEqualAndEndTimeGreaterThanEqual(groupName, DateUtil.parseDateStr(patrolTime.toString()), DateUtil.parseDateStr(patrolTime.toString()));
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String today = format.format(date);
        if (npGroupEntityList.size() > 0) {
            for (int i = 0; i < npGroupEntityList.size(); i++) {
                Long groupId = npGroupEntityList.get(i).getId();
                Date startPatrolTime = DateUtil.parseDateTimeStr(patrolTime.toString() + " " +npGroupEntityList.get(i).getStartTimePoint().toString());
                Date stopPatrolTime = DateUtil.parseDateTimeStr(patrolTime.toString() + " "  + npGroupEntityList.get(i).getEndTimePoint().toString());
                if (!npResultRepository.existsByGroupIdAndStartTimeBetween(groupId, startTime, stopTime)) {
                    //若记录表不存在则前往人员轨迹表查询人员轨迹
                    saveNpResultInfo(groupId, startPatrolTime, stopPatrolTime);
                } else if (today.equalsIgnoreCase(patrolTime)) {
                    NpResultEntity resultEntity = npResultRepository.getAllByGroupIdAndStartTimeBetween(groupId, startTime, stopTime);
                    npResultRepository.deleteById(resultEntity.getId());
                    saveNpResultInfo(groupId, startPatrolTime, stopPatrolTime);
                }
            }
        }
    }

    //获取前一天日期
    public String getForeDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());
        Date day = null;
        try {
            day = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ms = day.getTime() - 1 * 24 * 3600 * 1000L;
        Date prevDay = new Date(ms);
        String foreDate = dateFormat.format(prevDay);
        return foreDate;
    }

    @Override
    public Page<NpResultDetailEntity> getNpResultDetail(SearchCriteria criteria, Pageable pageable) {
        return npResultDetailRepository.search(criteria, pageable);
    }

    @Override
    public Page<NpResultDetailEntity> getNpResultDetailInfo(Long resultId, String personnelName, int type,
                                                            Long timeLength, PageParam pageParam, Pageable pageable) {

        String sql = "select * from np_result_detail where result_id =:resultId ";
        if (personnelName != null) {
            sql = sql + " and personnel_name like '%" + personnelName + "%' ";
        }
        if (timeLength != null) {
            //0等于，1大于，2小于
            if (type == 1) {
                sql = sql + " and time_length >= " + timeLength;
            } else if (type == 2) {
                sql = sql + " and time_length <= " + timeLength;
            }
        }
        sql = sql + " order by IFNULL(start_time, end_time) ";

        List<NpResultDetailEntity> list = entityManager.createNativeQuery(sql, NpResultDetailEntity.class)
                .setParameter("resultId", resultId)
                .getResultList();

        return new PageImpl<>(new ArrayList<>(list), pageable, list.size());
    }


}
